import {Component, OnDestroy, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {BaseConfigService} from '@base/services/config.service';
import {baseAnimations} from '@base/animations';
import {HttpClient} from '@angular/common/http';
import {Subscription} from 'rxjs';
import {Router} from '@angular/router';

import {MatSnackBar} from '@angular/material/snack-bar';


import {JwtHelperService} from '@auth0/angular-jwt';
import {baseConfig} from "../../../../base-config";


@Component({
    selector: 'login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    encapsulation: ViewEncapsulation.None,
    animations: baseAnimations
})
export class LoginComponent implements OnDestroy {
    loginForm: FormGroup;
    error = '';

    // #region fields
    type = 0;
    count = 0;

    /**
     * Constructor
     *
     * @param fb
     * @param {BaseConfigService} _baseConfigService
     * @param {FormBuilder} _formBuilder
     * @param http
     * @param _snackBar
     * @param router
     * @param jwtHelper
     */
    constructor(
        fb: FormBuilder,
        private _baseConfigService: BaseConfigService,
        private _formBuilder: FormBuilder,
        private http: HttpClient,
        private _snackBar: MatSnackBar,
        private router: Router,
        public jwtHelper: JwtHelperService
    ) {
        // Configure the layout
        if (localStorage.getItem('access_token')) {
            console.log(this.jwtHelper.isTokenExpired());// true or false
        }

        this.loginForm = fb.group({
            email: ['', [Validators.required, Validators.email]],
            password: ['', Validators.required],
            remember: [true],
        });
    }

    get email(): any {
        return this.loginForm.controls.email;
    }

    // #region get captcha

    get password(): any {
        return this.loginForm.controls.password;
    }

// #endregion

    switch(ret: any): any {
        this.type = ret.index;
    }

    openSnackBar(msg: string): any {
        this._snackBar.open(msg, 'End now', {
            duration: 5000,
            horizontalPosition: 'right',
            verticalPosition: 'top',
            panelClass: ['red-snackbar'],
        });
    }

    submit(): Subscription {
        this.error = '';

        this.email.markAsDirty();
        this.email.updateValueAndValidity();
        this.password.markAsDirty();
        this.password.updateValueAndValidity();
        if (this.email.invalid || this.password.invalid) {
            return;
        }

        // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
        // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
        this.http
            .post('http://api.catchadmin.com/login', {
                // type: this.type,
                email: this.email.value,
                password: this.password.value,
            })
            .subscribe((res: any) => {
                if (res.code !== 10000) {
                    this.error = res.message;
                    console.log(res.message);
                    this.openSnackBar(this.error);
                    return;
                }
                localStorage.setItem('access_token', res.data.token);
                console.log(res.message);
                this.http.get('http://api.catchadmin.com/user/info')
                    .subscribe((res2: any) => {
                        if (res2.code !== 10000) {
                            this.error = res2.message;
                            console.log(res2.message);
                            this.openSnackBar(res2.message);
                            return;
                        }
                        console.log(res2.data);
                    });
                this.router.navigateByUrl('/apps/dashboards/analytics');
                // 清空路由复用信息
                // this.reuseTabService.clear();
                // 设置用户Token信息
                // this.tokenService.set(res.user);
                // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
            });
    }

    /**
     * On init
     */
    ngOnDestroy(): void {
        this.loginForm = this._formBuilder.group({
            email: ['', [Validators.required, Validators.email]],
            password: ['', Validators.required]
        });
    }
}
